package cn.gjxblog.common.utils;

import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.Instant;

/**
 * @author gjx
 * @version v1.0
 * @Description 文件工具
 * @date 2018/12/7 15:22
 */
@Slf4j
public class FileUtil {

    public static String saveToLocal(String path, MultipartFile file){
        String relativePath = "/"+Instant.now().getEpochSecond()+"/"+file.getOriginalFilename();

        File  newFile = new File(path+relativePath);

        if(!newFile.exists()){
            newFile.getParentFile().mkdirs();
            try {
                newFile.createNewFile();
            } catch (IOException e) {
                log.error("创建文件夹失败");
                e.printStackTrace();
                throw  new  RuntimeException("上传文件失败");
            }
        }
        try {
            Files.write(file.getBytes(),newFile);
        } catch (IOException e) {
            log.error("写入文件失败");
            e.printStackTrace();
            throw  new  RuntimeException("上传文件失败");
        }

        return relativePath;
    }
}
